<template>
    <rui-page :defines="defines">
        <rui-query :label-width="150"
                   ref="searchForm"
                   :query="queryData"
                   :query-rows="searchFormOptions"
        >
            <template slot="departmentTitle" slot-scope="{ key,data }">
                <span style="line-height: 32px">
                    <Cascader style="width: 200px" :data="department" :load-data="loadData"
                              @on-change="handleChangeDep" change-on-select filterable v-model="data[key]"></Cascader> 
                </span>
            </template>
            <template slot="createTimes" slot-scope="{ key,data }">
                <DatePicker v-model="data[key]" type="daterange" format="yyyy-MM-dd" clearable
                            @on-change="selectDateRange" placeholder="选择起始时间"
                            style="width: 200px"></DatePicker>
            </template>
        </rui-query>
        <Row>
            <Alert show-icon>
                已选择 <span class="select-count">{{selectCount}}</span> 项
                <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert>
        </Row>
        <rui-table
            :defineId="'userDefine'"
            :columns="userColumns"
            :fixedLeft="['action']"
            :showIndex="false"
            :select="true"
            :slots="[{key:'action',slot:'action'},{key:'lockFlag',slot:'lockFlag'}]"
            @loadDatas="queryData"
            ref-query="searchForm"
            @on-selection-change="changeSelect"
            ref="userTable"
        >
            <template slot="toolBar">
                <Button @click="add" icon="md-add" type="primary">新增</Button>
                <Button @click="upAll" icon="md-remove-circle">批量禁用</Button>
                <Button @click="refresh" type="primary">刷新</Button>
            </template>
            <template slot="action" slot-scope="{ row }">
                <div>
                    <Button @click="edit(row)" size="small" type="primary">编辑</Button>
                    <!-- <Button v-if="row.lockFlag==='0'" type="warning" size="small" @click="disable(row)">禁用
                    </Button>
                    <Button v-if="row.lockFlag==='9'" type="success" size="small" @click="enable(row)">启用
                    </Button> -->
                </div>
            </template>
            <template slot-scope="{ row }" slot="lockFlag">
                <div>
                    <tag v-if="row.lockFlag=='0'" color="success" size="default">启用</tag>
                    <tag v-if="row.lockFlag=='9'" color="warning" size="default">禁用</tag>
                </div>
            </template>
        </rui-table>
        <Modal
            v-model="userModalVisible"
            :title="modalTitle"
            :width="900"
            :closable="false"
            :mask-closable="false"
            @on-ok="submitUser"
        >
            <rui-form :form-options="userFormOptions" :read-only="false" ref="userForm">
                <template slot="departmentTitle" slot-scope="{ key,data }">
                    <Poptip trigger="click" placement="right" title="选择部门" width="250">
                        <div style="display:flex;">
                            <Input v-model="data[key]" readonly clearable @on-clear="clearSelectDep"
                                   style="margin-right:10px;width: 200px;" placeholder="选择所属部门"/>
                        </div>
                        <div slot="content" class="tree-bar">
                            <Input v-model="searchKey" suffix="ios-search" @on-change="searchDp" placeholder="输入部门名搜索"/>
                            <Tree :data="department" :load-data="loadDataTree" @on-select-change="selectTree"></Tree>
                        </div>
                    </Poptip>
                </template>
                <template slot="newRoleIds" slot-scope="{ key,data }">
                    <Select style="width: 200px" v-model="data[key]" multiple @on-open-change="loadNewRole">
                        <Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.roleName">
                            <span style="margin-right:5px;">{{ item.roleName }}</span>
                            <span>{{ item.roleCode }}</span>
                        </Option>
                    </Select>
                </template>
                <template slot="oldRoleIds" slot-scope="{ key,data }">
                    <Select style="width: 200px" v-model="data[key]" multiple @on-open-change="loadOldRole">
                        <Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.roleName">
                            <span style="margin-right:5px;">{{ item.roleName }}</span>
                            <span>{{ item.roleCode }}</span>
                        </Option>
                    </Select>
                </template>
            </rui-form>
            <div slot="footer">
                <Button size="small" @click="cancel">取消</Button>
                <Button type="primary" size="small" @click="submitUser">提交</Button>
            </div>
        </Modal>
    </rui-page>
</template>
<script>
    import userDefine from "./user-define";
    import {
        addUser,
        editUser,
        enableUser,
        deleteUser,
        disableUser,
        getUserListData,
        upAllByIds
    } from "_p/afs-apply/api/apply-admin/manage-user/user";

    import {
        getDeptByParentId,
        searchDepartment
    } from "_p/afs-apply/api/apply-admin/department/department";

    import {
        initAll,
        initAppertainRegion,
        searchAppertainRegion
    } from "_p/afs-apply/api/apply-admin/appertain-region/appertainRegion";

    import {
        getAllRoleList
    } from "_p/afs-apply/api/apply-admin/role/role";

    import {deepClone} from '@/libs/utils/ObjectClone';

    export default {
        name: "user-manage",
        data() {
            return {
                deptId: "",
                userModalVisible: false,
                department: [],
                modalType: null,
                roleList: [],
                searchKey: "",
                appIds: [],
                autIds: [],
                modalTitle: "用户新增",
                searchFormOptions: [
                    {defineId: "userDefine", fields: ["userRealName", "searchPhone", "searchEmail"]},
                    {
                        defineId: "userDefine", fields: ["deptId", "lockFlag", "createTimes"],
                        slots: [{key: 'deptId', slotName: 'departmentTitle'},
                            {key: 'createTimes', slotName: 'createTimes'}]
                    },
                ],
                userColumns: ["action", "username", "userRealName", "departmentTitle", "lockFlag", "identityNumber",
                    "phone", "userEmail", "createTime"],
                userFormOptions: [
                    {
                        grids: [
                            {
                                defineId: "userDefine",
                                span: 10,
                                fields: ["userRealName", "username", "phone", "newRoleIds"],
                            },
                            {
                                defineId: "userDefine",
                                span: 10,
                                fields: ["departmentTitle", "userEmail", "identityNumber", "oldRoleIds"],
                                slots: [{key: 'departmentTitle', slotName: 'departmentTitle'},
                                    {key: 'newRoleIds', slotName: 'newRoleIds'},
                                    {key: 'oldRoleIds', slotName: 'oldRoleIds'}],
                            }
                        ]
                    }
                ],
                selectCount: 0,
            };
        },
        computed: {
            defines() {
                return [
                    {
                        id: "userDefine",
                        fields: userDefine
                    }
                ];
            }
        },
        methods: {
            queryData(queryData) {
                getUserListData(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.userTable.updateTableData(records, total);
                    }
                });
            },
            selectDateRange(v) {
                if (v) {
                    this.$refs.searchForm.setFiledValue("startDate", v[0]);
                    this.$refs.searchForm.setFiledValue("endDate", v[1]);
                }
            },
            refresh() {
                this.$refs['userTable'].reloadData();
                this.clearSelectAll();
            },
            clearSelectAll() {
                this.$refs.userTable.getTable().selectAll(false);
            },
            initDepartmentData() {
                getDeptByParentId('0').then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.value = e.id;
                                e.label = e.title;
                                e.loading = false;
                                e.children = [];
                            } else {
                                e.value = e.id;
                                e.label = e.title;
                            }
                            if (e.status === '0') {
                                e.label = "[已禁用] " + e.title;
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                        });
                        this.department = res.data;
                    }
                });
            },
            loadData(item, callback) {
                item.loading = true;
                getDeptByParentId(item.value).then(res => {
                    item.loading = false;
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.value = e.id;
                                e.label = e.title;
                                e.loading = false;
                                e.children = [];
                            } else {
                                e.value = e.id;
                                e.label = e.title;
                            }
                            if (e.status === '0') {
                                e.label = "[已禁用] " + e.title;
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                        });
                        item.children = res.data;
                        callback();
                    }
                });
            },
            handleChangeDep(value) {
                // 获取最后一个值
                if (value && value.length > 0) {
                    this.$refs.searchForm.setFiledValue("deptId", value[value.length - 1]);
                } else {
                    this.$refs.searchForm.setFiledValue("deptId", "");
                }
            },
            loadOldRole(val){
                if(val){
                    this.getRoleList("old");
                }
            },
            loadNewRole(val){
                if(val){
                    this.getRoleList("new");
                }
            },
            getRoleList(val) {
                if(!this.deptId){
                    this.$Message.warning("请先选择所属部门");
                    return false;
                }
                getAllRoleList(val).then(res => {
                    if (res.code === "0000") {
                        this.roleList = res.data;
                    }
                });
            },
            changeSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            add() {
                this.initDepartmentData();

                this.$refs.userForm.resetFrom();
                this.modalType = 0;
                this.modalTitle = "用户新增";
                this.$refs.userForm.setAllFieldRequired(true);
                this.$refs.userForm.setFieldRequired("userEmail",false);

                this.$refs.userForm.setFieldReadOnly("username", false);
                this.$refs.userForm.setFieldReadOnly("identityNumber", false);
                this.$refs.userForm.setFiledHide("newRoleIds",true);
                this.$refs.userForm.setFiledHide("oldRoleIds",true);
                this.$nextTick(() => {
                    this.$refs.userForm.resetFrom();
                })
                this.userModalVisible = true;
            },
            edit(row) {
                console.log(row)
                if(this.$store.getters.userInfo.userId===row.userId){
                    this.$Message.success("不能修改自己的账户！！！");
                    return false;
                }
                let data = deepClone(row);
                data['oldRoleIds'] = [];
                data['newRoleIds'] = [];
                this.modalType = 1;
                this.modalTitle = "用户编辑";
                this.$refs.userForm.updateFormData(data);
                this.$refs.userForm.setFieldReadOnly("username", true);
                this.$refs.userForm.setFieldReadOnly("identityNumber", true);
                let selectNewRolesId = [];
                let selectOldRolesId = [];
                this.deptId = row.deptId;
                if(row.oldRoles.length>0){
                    this.$refs.userForm.setFiledHide("oldRoleIds",false);
                    getAllRoleList("old").then(res => {
                        if (res.code === "0000") {
                            this.roleList = res.data;
                            row.oldRoles.forEach(function (e) {
                                selectNewRolesId.push(e.id);
                            });
                            this.$refs.userForm.setFiledValue("oldRoleIds", selectNewRolesId);
                        }
                    });
                }else{
                    this.$refs.userForm.setFiledHide("oldRoleIds",true);
                }
                if(row.newRoles.length>0){
                    this.$refs.userForm.setFiledHide("newRoleIds",false);
                    getAllRoleList("new").then(res => {
                        if (res.code === "0000") {
                            this.roleList = res.data;
                            row.newRoles.forEach(function (e) {
                                selectOldRolesId.push(e.id);
                            });
                            this.$refs.userForm.setFiledValue("newRoleIds", selectOldRolesId);
                        }
                    });
                }else{
                    this.$refs.userForm.setFiledHide("newRoleIds",true);
                }

                this.$refs.userForm.setAllFieldRequired(true);
                this.$refs.userForm.setFieldRequired("userEmail",false);
                this.userModalVisible = true;
            },
            enable(v) {
                this.$Modal.confirm({
                    title: "确认启用",
                    content: "您确认要启用用户 " + v.username + " ?",
                    onOk: () => {
                        enableUser(v.userId).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            disable(v) {
                if(this.$store.getters.userInfo.userId===v.userId){
                    this.$Message.success("不能禁用自己的账户！！！");
                    return false;
                }
                this.$Modal.confirm({
                    title: "确认禁用",
                    content: "您确认要禁用用户 " + v.username + " ?",
                    onOk: () => {
                        disableUser(v.userId).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            clearSelectDep() {
                this.$refs.userForm.setFiledValue("deptId", "");
                this.$refs.userForm.setFiledValue("departmentTitle", "");
            },
            searchDp() {
                // 搜索部门
                if (this.searchKey) {
                    searchDepartment(this.searchKey).then(res => {
                        if (res.code === "0000") {
                            res.data.forEach(function (e) {
                                if (e.isParent) {
                                    e.loading = false;
                                    e.children = [];
                                }
                                if (e.status === '0') {
                                    e.title = "[已禁用] " + e.title;
                                    e.disabled = true;
                                }
                            });
                            this.department = res.data;
                        }
                    });
                } else {
                    this.initDepartmentData();
                }
            },

            loadDataTree(item, callback) {
                getDeptByParentId(item.id).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.loading = false;
                                e.children = [];
                            }
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                        });
                        callback(res.data);
                    }
                });
            },
            selectTree(v) {
                if (v.length > 0) {
                    // 转换null为""
                    for (let attr in v[0]) {
                        if (v[0][attr] === null) {
                            v[0][attr] = "";
                        }
                    }
                    let str = JSON.stringify(v[0]);
                    let data = JSON.parse(str);
                    this.deptId = data.id;
                    this.$refs.userForm.setFiledValue("deptId", data.id);
                    this.$refs.userForm.setFiledValue("departmentTitle", data.title);
                    if(!Object.prototype.hasOwnProperty.call(v[0],"newCarRegion")||v[0].newCarRegion.length==0){
                        this.$refs.userForm.setFiledHide("newRoleIds",true);
                    }else{
                        this.$refs.userForm.setFiledHide("newRoleIds",false);
                    }
                    if(!Object.prototype.hasOwnProperty.call(v[0],"oldCarRegion")||v[0].oldCarRegion.length==0){
                        this.$refs.userForm.setFiledHide("oldRoleIds",true);
                    }else{
                        this.$refs.userForm.setFiledHide("oldRoleIds",false);
                    }

                }
            },
            cancel() {
                this.userModalVisible = false;
            },
            submitUser() {
                this.$refs.userForm.getForm().validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            addUser(this.$refs.userForm.getFormData()).then(res => {
                                if (res.code === "0000") {
                                    this.$Message.success(res.msg);
                                    this.userModalVisible = false;
                                    this.refresh();
                                }
                            }).catch(() => {
                                this.refresh();
                            });
                        } else {
                            // 编辑
                            editUser(this.$refs.userForm.getFormData()).then(res => {
                                if (res.code === "0000") {
                                    this.$Message.success(res.msg);
                                    this.userModalVisible = false;
                                    this.refresh();
                                }
                            }).catch(() => {
                                this.refresh();
                            });
                        }
                    }
                });
            },

            // 批量停用
    upAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您还未选择要停用的数据");
        return;
      }
      for (var i = 0; i < this.selectList.length; i++) {
        if(this.$store.getters.userInfo.userId===this.selectList[i].userId){
            this.$Message.success("不能禁用自己的账户！！！");
            return false;
        }
      }
      
    //   for (var i = 0; i < this.selectList.length; i++) {
    //     if (this.selectList[i].status != "00") {
    //       this.$Message.warning("只有启用的才可以停用，请重新选择！");
    //       this.clearSelectAll();
    //       return;
    //     }
    //   }
      this.$Modal.confirm({
        title: "确认停用",
        content: "您确认要停用所选的 " + this.selectCount + " 条数据?",
        onOk: () => {
          let ids = [];
          this.selectList.forEach(function(e) {
            ids += e.userId + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          this.operationLoading = true;
          upAllByIds(ids).then(res => {
            this.operationLoading = false;
            if (res.code === "0000") {
              this.$Message.success("停用成功");
              this.clearSelectAll();
              this.refresh();
            }
          });
        }
      });
    }
        },
        mounted() {
            this.refresh();
            this.initDepartmentData();
        }
    };
</script>
